package es.capgemini.extjsplugin.core;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;

import es.capgemini.extjsplugin.wizard.GeneratorWizardModel;

/**
 * Clase para lanzar la generacion de los componentes desde el wizard
 * @author Lisandro Medrano
 *
 */
public class ExtJSFormBuilder implements IRunnableWithProgress {
	
	
	private GeneratorWizardModel model;
	
	
    private DaoGenerator daoGenerator;
    private FormJSPGenerator formGenerator;
    private ListadoJSPGenerator jspGenerator;
    private ManagerGenerator managerGenerator;
	/**
	 * 
	 * @param model El modelo sobre el cual se van a generar los componentes
	 */
	public ExtJSFormBuilder(GeneratorWizardModel model) {
		this.model=model;
	}
	
	@Override
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		//crearEstructuraDirectorio();
		monitor.beginTask("Wait..", 100);
		if(model.isAltaEdicionForm()){
			monitor.setTaskName("Creando Formularios");
			monitor.worked(10);
			formGenerator=new FormJSPGenerator(model);
			if(model.isFlow())
				formGenerator.crearFlow();
			formGenerator.crearJSPForm();
		}
		if(monitor.isCanceled())return;
		if(model.isManager()){
			monitor.setTaskName("Creando Manager");
			monitor.worked(20);
			managerGenerator=new ManagerGenerator(model);
			managerGenerator.crearManager();
			managerGenerator.managerCodeGeneration();
		}
		if(monitor.isCanceled())return;
		if(model.isDao()){
			monitor.worked(30);
			monitor.setTaskName("Creando Dao");
			String class_name=model.getMyClass().getSimpleName();
			daoGenerator=new DaoGenerator(model);
			daoGenerator.crearDao(class_name);
			daoGenerator.crearDaoImpl(class_name);
		}
		if(monitor.isCanceled())return;
		if(model.isDto()){
			monitor.worked(40);
			monitor.setTaskName("Creando Dto");
			if(managerGenerator==null)
				managerGenerator=new ManagerGenerator(model);
			managerGenerator.crearDto();
		}
		if(monitor.isCanceled())return;
		if(model.isListado()){
			monitor.setTaskName("Creando Listado");
			monitor.worked(50);
			jspGenerator=new ListadoJSPGenerator(model);
			if(model.isFlow())
				jspGenerator.crearFlowListado();
			jspGenerator.crearJSON();
			jspGenerator.crearListadoJSP();
		}
		if(monitor.isCanceled())return;
		try {
			monitor.setTaskName("Refreshing workspace");
			monitor.worked(60);
			if(monitor.isCanceled())return;
			ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IFolder.DEPTH_INFINITE, null);
			if(monitor.isCanceled())return;
			monitor.done();
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}    
    
}
